package com.nep.service.impl;

import com.nep.entity.GridMember;
import com.nep.io.FileIO;
import com.nep.service.GridMemberService;
import java.io.File;
import java.util.List;

public class GridMemberServiceImpl implements GridMemberService {
    @Override
    public GridMember login(String loginCode, String password) {
        System.out.println("=== 开始登录验证 ===");
        System.out.println("登录账号: " + loginCode);
        
        // 检查文件是否存在
        File file = new File("gridmember.txt");
        if (!file.exists()) {
            System.out.println("错误: gridmember.txt 文件不存在");
            return null;
        }
        
        if (file.length() == 0) {
            System.out.println("错误: gridmember.txt 文件为空");
            return null;
        }
        
        // 读取数据
        Object obj = FileIO.readObject("gridmember.txt");
        if (obj == null) {
            System.out.println("错误: 读取数据失败，返回null");
            return null;
        }
        
        if (!(obj instanceof List)) {
            System.out.println("错误: 读取的数据不是List类型，而是: " + obj.getClass().getName());
            return null;
        }
        
        List<?> glist = (List<?>) obj;
        System.out.println("读取到的网格员列表: " + glist.size() + " 条记录");
        
        // 验证登录
        for (Object item : glist) {
            if (!(item instanceof GridMember)) {
                System.out.println("警告: 跳过非GridMember对象: " + item.getClass().getName());
                continue;
            }
            
            GridMember gm = (GridMember) item;
            System.out.println("检查网格员: " + gm.getLoginCode());
            
            if (gm.getLoginCode() != null && gm.getPassword() != null &&
                gm.getLoginCode().equals(loginCode) && gm.getPassword().equals(password)) {
                System.out.println("登录成功: " + gm.getRealName());
                return gm;
            }
        }
        
        System.out.println("登录失败: 未找到匹配的账号和密码");
        return null;
    }
}
